import os

from django.conf import settings

from apps.contents.models import ContentCategory
from apps.contents.utils import get_categories
from django.template import loader

def generate_static_index_html():
    print('每隔一分钟一次')
    #获取首页数据
    # 显示商品三级分类
    categories = get_categories()

    # 显示广告
    ad_categories = ContentCategory.objects.all()
    contents = {}
    for ad in ad_categories:
        contents[ad.key] = ad.content_set.filter(status=True).order_by('sequence')

    context = {
        'categories': categories,
        'contents': contents
    }
    #获取模板文件
    template = loader.get_template('index.html')

    #渲染拼接
    html_text = template.render(context)

    #写入文件
    file_path = os.path.join(settings.STATICFILES_DIRS[0], 'index.html')
    with open(file_path, 'w') as f:
        f.write(html_text)
